#include "DispatcherThread.h"
#include "McuRPCManager.h"
#include <log/log.h>

namespace android {

DispatcherThread::DispatcherThread(McuRPCManager* manager, int hw_type, BufferQueue<McuRPCBuffer>* queue)
{
    mManager = manager;
    mHwType = hw_type;
    mBufferQueue = queue;
}

DispatcherThread::~DispatcherThread() {

}

void DispatcherThread::start() {
    this -> run("DispatcherThread", PRIORITY_HIGHEST);
}

void DispatcherThread::onDataReady() {
    mBarrier.open();
}

void DispatcherThread::registerRPCHandler(McuRPCHandler* handler) {
    mHandler = handler;
}

void DispatcherThread::stop() {
    requestExitAndWait();
}

/*
 * return true if wheel control handled
 * return false if no wheel control
 */
int DispatcherThread::processWheelControl(McuRPCBuffer* buf) {

    // no wheel control message
    return false;
}

bool DispatcherThread::threadLoop() {
    mBarrier.wait();
    mBarrier.close();

    McuRPCBuffer* buf = mBufferQueue -> dequeueConsumerBuffer();

    if (mHwType == McuRPCManager::RPC_UART) {
        // handle wheel control message
        if (processWheelControl(buf)) {
            mBufferQueue -> enqueueProducerBuffer(buf);
            return true;
        }
    }

    //handle
    if (mHandler != NULL) {
        mHandler -> process(buf);
    }

    mBufferQueue -> enqueueProducerBuffer(buf);
    return true;
}


} //namespace
